package com.lzh.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author zhehen.lu
 * @date 2025/8/3 14:12
 */
public class EasyExcelDateConverter implements Converter<Date> {
    private static String PATTERN_YYYY_MM_DD = "yyyy-MM-dd";

    public EasyExcelDateConverter() {
    }

    @Override
    public Class<Date> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(ReadConverterContext<?> context) throws Exception {
        ReadCellData<?> cellData = context.getReadCellData();
        LocalDate localDate;
        if (cellData.getType().equals(CellDataTypeEnum.NUMBER)) {
            localDate = LocalDate.of(1900, 1, 1);
            localDate = localDate.plusDays(cellData.getNumberValue().longValue() - 2L);
            return this.localDate2Date(localDate);
        } else if (cellData.getType().equals(CellDataTypeEnum.STRING)) {
            localDate = LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            return this.localDate2Date(localDate);
        } else {
            return null;
        }
    }

    @Override
    public WriteCellData<String> convertToExcelData(WriteConverterContext<Date> context) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
        return new WriteCellData(dateFormat.format((Date)context.getValue()));
    }

    private Date localDate2Date(LocalDate localDate) {
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        return Date.from(zonedDateTime.toInstant());
    }
}

